package com.rgs.gateway.web.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @author RenGaoshuai
 * @date 2024/7/1 16:42
 * @description
 */
@Slf4j
public class GatewaySignUtils {

    /**
     * 排序方法
     * @param obj
     * @return
     */
    public static Object sortJson(Object obj) {
        if (obj instanceof Map) {
            Map<String, Object> jsonMap = (Map<String, Object>) obj;
            JSONObject sortedJsonObject = new JSONObject(true);
            List<String> keys = new ArrayList<>(jsonMap.keySet());
            keys.sort(Comparator.naturalOrder());
            for (String key : keys) {
                if(key.equals("multipartFile")){
                    continue;
                }
                if(key.equals("contractByteStr")) {
                    continue;
                }
                Object value = jsonMap.get(key);
                if (value instanceof Map || value instanceof List) {
                    value = sortJson(value);
                }
                sortedJsonObject.put(key, value);
            }
            return sortedJsonObject;
        } else if (obj instanceof List) {
            List<Object> jsonArray = (List<Object>) obj;
            JSONArray sortedJsonArray = new JSONArray();
            for (Object value : jsonArray) {
                if (value instanceof Map || value instanceof List) {
                    value = sortJson(value);
                }
                sortedJsonArray.add(value);
            }
            return sortedJsonArray;
        } else {
            return obj;
        }
    }

    /**
     * 字节数组拼接
     * @param x1
     * @param x2
     * @return
     */
    public static byte[] concatenate(byte[] x1, byte[] x2)   {
        byte[] result = new byte[x1.length + x2.length];
        System.arraycopy(x1, 0, result, 0, x1.length);
        System.arraycopy(x2, 0, result, x1.length, x2.length);
        return result;
    }
}
